package org.seckill.service;

import org.apache.commons.collections.MapUtils;
import org.seckill.custommapper.SeckillCustomMapper;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.enums.SeckillStateEnum;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import org.seckill.logic.RedisLogic;
import org.seckill.mapper.SeckillMapper;
import org.seckill.mapper.SeckillViewMapper;
import org.seckill.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Wrb
 * @date 2019/7/3 15:11
 */
@Service
public class SeckillService {

	@Autowired
	private SeckillMapper seckillMapper;

	@Autowired
	private SeckillCustomMapper seckillCustomMapper;

	@Autowired
	private SuccessKilledService successKilledService;

	@Autowired
	private SeckillViewMapper seckillViewMapper;

	@Autowired
	private RedisLogic redisLogic;

	private Logger logger = LoggerFactory.getLogger(SeckillService.class);

	private final String slat = "kfjihnv9w8u304k2gG$#L:F#330-g33r?{f43fh9093g0";

	public int insert(Seckill seckill) {
		return this.seckillMapper.insertSelective(seckill);
	}

	/**
	 * 查询单个秒杀记录
	 *
	 * @param seckillId
	 * @return
	 */
	public Seckill selectSeckillByKey(Long seckillId) {
		return this.seckillMapper.selectByPrimaryKey(seckillId);
	}

	/**
	 * 查询秒杀列表
	 *
	 * @return
	 */
	public List<Seckill> getSeckillList() {
		SeckillCriteria cr = new SeckillCriteria();
		String orderString = String.format(" start_time desc limit %d,%d", 0, 4);
		cr.setOrderByClause(orderString);
		return this.seckillMapper.selectByExample(cr);
	}

	/**
	 * 秒杀开启时输出秒杀地址，否则输出系统时间和秒杀开启时间
	 *
	 * @param seckillId
	 */
	public Exposer exportSeckillUrl(Long seckillId) {
		// 优化点 ： 缓存优化
		//1. get seckill from redis
		Seckill seckill = redisLogic.getSeckill(seckillId);
		if (seckill == null) {
			//2. get seckill from db
			seckill = this.selectSeckillByKey(seckillId);
			if (seckill == null) {
				return new Exposer(false, seckillId);
			} else {
				//3. set seckill in redis
				redisLogic.putSeckill(seckill);
			}
		}

		Date startTime = seckill.getStartTime();
		Date endTime = seckill.getEndTime();
		//当前时间
		Date nowTime = new Date();
		if (nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()) {
			return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
		}
		//转化特定字符串的过程
		String md5 = getMD5(seckillId);
		return new Exposer(true, md5, seckillId);
	}

	@Transactional
	public SeckillExecution exeuteSeckill(Long seckillId, Long userPhone, String md5)
			throws SeckillException, RepeatKillException, SeckillCloseException {
		if (md5 == null || !md5.equals(getMD5(seckillId))) {
			throw new SeckillException("seckill data rewrite");
		}
		//执行秒杀逻辑
		Date nowTime = new Date();
		try {
			//记录购买行为
			SuccessKilled successKilled = new SuccessKilled();
			successKilled.setSeckillId(seckillId);
			successKilled.setUserPhone(userPhone);
			successKilled.setState((byte) 0);
			int insertCount = successKilledService.insertSuccessKilled(successKilled);
			if (insertCount <= 0) {
				//重复秒杀
				throw new RepeatKillException("seckill repeated");
			} else {
				//减库存，热点商品竞争 rollback
				int updateCount = seckillCustomMapper.reduceNumber(seckillId, nowTime);
				if (updateCount <= 0) {
					//没有更新都记录，秒杀结束
					throw new SeckillCloseException("seckill is closed");
				} else {
					//秒杀成功 commit
					SeckillViewCriteria cr = new SeckillViewCriteria();
					cr.or().andSeckillIdEqualTo(seckillId).andUserPhoneEqualTo(userPhone);
					List<SeckillView> seckillViews = seckillViewMapper.selectByExample(cr);
					return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, seckillViews.get(0));
				}

			}


		} catch (SeckillCloseException | RepeatKillException e1) {
			throw e1;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			//所有编译期异常 转化为运行期异常
			throw new SeckillException("seckill inner error : " + e.getMessage());
		}
	}

	private String getMD5(Long seckillId) {
		String base = seckillId + "/" + slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		return md5;
	}

	public SeckillExecution executeSeckillProcedure(Long seckillId, Long userPhone, String md5) {
		if (md5 == null || !md5.equals(getMD5(seckillId))) {
			throw new SeckillException("seckill data rewrite");
		}
		//执行秒杀逻辑
		Date killTime = new Date();
		Map<String, Object> map = new HashMap<>();
		map.put("seckillId", seckillId);
		map.put("userPhone", userPhone);
		map.put("killTime", killTime);
		map.put("result", null);
		try {
			seckillCustomMapper.killByProcedure(map);
			// 获取result
			int result = MapUtils.getInteger(map, "result", -2);
			if (result == 1) {
				//秒杀成功
				SeckillViewCriteria cr = new SeckillViewCriteria();
				cr.or().andSeckillIdEqualTo(seckillId).andUserPhoneEqualTo(userPhone);
				List<SeckillView> seckillViews = seckillViewMapper.selectByExample(cr);
				return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, seckillViews.get(0));
			}else {
				return new SeckillExecution(seckillId, SeckillStateEnum.stateOf(result));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new SeckillExecution(seckillId, SeckillStateEnum.INNER_ERROR);
		}
	}
}
